package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApAuthor;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author syn
 * @since 2021-12-29
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
//        先确定用户名或密码是否为空
        if (dto == null && StringUtils.isNotBlank(dto.getEquipmentId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        Map resultMap = new HashMap();
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {

            //        根据用户名查用户
            LambdaQueryWrapper<ApUser> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser apUser = this.baseMapper.selectOne(queryWrapper);
//        如果查不到返回结果
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
//        如果能查到在比较密码
            String password = dto.getPassword() + apUser.getSalt();
            password = DigestUtils.md5Hex(password);
//        页面传过来的密码是明文的，我们需要加密，加密的时候为了更安全我们给每个人的密码上加不同的盐
            if (!StringUtils.equals(password, apUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //        根据接口文档上的要求，data数据的位置需要返回 user和token
            apUser.setSalt("");
            apUser.setPassword("");
            apUser.setPhone("");
            resultMap.put("user", apUser);

            Map claimMaps = new HashMap();
            claimMaps.put("userId", apUser.getId());
            claimMaps.put("name", apUser.getName());
            String token = AppJwtUtil.getToken(claimMaps);
            resultMap.put("token", token);
            return ResponseResult.okResult(resultMap);
        } else {
            Map claimMaps = new HashMap();
            claimMaps.put("userId", 0);
            String token = AppJwtUtil.getToken(claimMaps);
            resultMap.put("token", token);
            return ResponseResult.okResult(resultMap);
        }

    }

    @Autowired
    private IApUserFollowService userFollowService;
    @Autowired
    private ArticleFeign articleFeign;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        User user = UserThreadLocalUtil.get();
        if(dto.getOperation()==0){  //关注
            ApUserFollow userFollow = new ApUserFollow();
            userFollow.setUserId(user.getUserId()); //当前登录人
            userFollow.setUserName(user.getName());
            userFollow.setFollowId(dto.getAuthorId()); //关注的文章作者id
            //        根据文章作者的id获取文章作者对象
            ResponseResult<ApAuthor> responseResult = articleFeign.getAuthorById(dto.getAuthorId());
            userFollow.setFollowName(responseResult.getData().getName()); //关注的文章作者姓名
            userFollow.setCreatedTime(new Date());

            //        下面5个值先随便给
            userFollow.setLevel(1);
            userFollow.setIsNotice(true);
            userFollow.setIsShieldComment(false);
            userFollow.setIsDisplay(true);
            userFollow.setIsShieldLetter(false);

            userFollowService.save(userFollow);
        }else{ //取消关注
//            delete from user_follow where user_id=?? and follow_id=??
            LambdaQueryWrapper<ApUserFollow> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUserFollow::getUserId,user.getUserId());
            queryWrapper.eq(ApUserFollow::getFollowId,dto.getAuthorId());
            userFollowService.remove(queryWrapper);
        }


        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setFollowId(dto.getAuthorId());
        followBehaviorDto.setEquipmentId(dto.getEquipmentId());
        followBehaviorDto.setUserId(user.getUserId());
        followBehaviorDto.setOperation(dto.getOperation());

        kafkaTemplate.send(followBehaviorTopic, JSON.toJSONString(followBehaviorDto));


        return ResponseResult.okResult();
    }
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Value("${topic.followBehaviorTopic}")
    private String followBehaviorTopic;
}

